<template>
  <div class="tree-select">
    <div class="tree-select-header">
      <span class="tree-select-title">当前选择：</span>
      <span class="selected-path">{{ selectedLabels.join(' -> ') }}</span>
    </div>
    <ul class="tree-list">
      <tree-node
          v-for="node in treeData"
          :key="node.id"
          :expanded-nodes="expandedNodes"
          :level="0"
          :node="node"
          :parent-labels="[]"
          @toggle-node="toggleNode"
          @transmit-selection="handleTransmitSelection"
      ></tree-node>
    </ul>
  </div>
</template>

<script lang="ts" setup>
import {defineEmits, defineProps, ref} from 'vue';
import TreeNode from './TreeNode.vue';

interface Node {
  id: string;
  label: string;
  children?: Node[];
}

const props = defineProps<{ treeData: Node[] }>();

const emit = defineEmits<{ (e: 'nodeSelected', nodeIds: string[]): void }>();

const expandedNodes = ref<{ [key: string]: boolean }>({});
const selectedLabels = ref<string[]>([]); // 保存被点击节点的层级 label 序列

const toggleNode = (id: string) => {
  expandedNodes.value[id] = !expandedNodes.value[id];
};

const handleTransmitSelection = (selection: { labels: string[], ids: string[] }) => {
  selectedLabels.value = selection.labels;
  emit('nodeSelected', selection.ids);
};
</script>

<style scoped>
.tree-select-header {
  position: relative;
  white-space: nowrap;

  .selected-path {
    font-weight: bold;
  }
}
</style>
